//
//  HomeViewController.swift
//  新浪微博
//
//  Created by mac on 15/11/26.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

private let HomeCellID = "homecell"
class HomeViewController: BaseViewController {
    
    
    //添加数组属性
    private lazy var statuses = [Statues]()
    override func viewDidLoad() {
        super.viewDidLoad()
        if !userLogin{
       vistorloginView?.setWithInfo("关注一些人,你回知道的更过", imagename: nil)
            return
        }
        
        //准备tableview
        prepareTablbeView()
        
       loadData { (statuses) -> () in
        guard let list = statuses else{
            SVProgressHUD.showErrorWithStatus(appErrorTip)
        return
        }
        //记录数组
        self.statuses = list
        //刷新表格
        self.tableView.reloadData()
    }
}

//MARK 加载数据
        private func loadData(finished: (statuses: [Statues]?)->()){
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
            guard let token = UserAccountViewModel().token else{
                SVProgressHUD.showErrorWithStatus("请求失败,请检查网络")
            return
            }
            let parameters = ["access_token": token]
            let afn = AFHTTPSessionManager()
            afn.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
                guard let array = result["statuses"] as? [[String: AnyObject]] else{
                    print("数据类型错误")
                    //错误的回调一定要执行
                    finished(statuses: nil)
                return
              }
                var list = [Statues]()
                for item in array{
                //字典转模型
                    //实例化容器数组
                    let s = Statues(dict: item)
                    list.append(s)
                }
                //执行回掉
                finished(statuses: list)
                }) { (_, error) -> Void in
                    finished(statuses: nil)
                    print(error)
            }
        }
    

    
    private func prepareTablbeView(){
    //注册cell
        tableView.registerClass(StatusesCell.self, forCellReuseIdentifier: HomeCellID)
        //设置tableview 自动计算行高,必须对容器视图有个自上而下的约束
        //设置预估行高
        
        tableView.estimatedRowHeight = 300
        //设置行高自动计算
        tableView.rowHeight = UITableViewAutomaticDimension
//        tableView.separatorStyle = .None

    }

    // MARK: - Table view data source


    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return statuses.count
    }

  
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //如果是用这个方法,需要程序源手动注册cell
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellID, forIndexPath: indexPath) as! StatusesCell

        cell.status = statuses[indexPath.row]
        

        return cell
    }
  

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
